package com.whmnx.chitchat.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSON;
import com.microsoft.signalr.Action1;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.HubConnectionState;
import com.microsoft.signalr.OnClosedCallback;
import com.orhanobut.logger.Logger;
import com.whmnx.chitchat.bean.MessageBean;
import com.whmnx.chitchat.bean.MessagePackBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import butterknife.Action;
import io.reactivex.Single;

/**
 * author : huang
 * date   : 2020/8/12 0012 18:07
 * version: 1.0
 * @author Administrator
 */
public class HubConnectionUtils {
    public static HubConnection hubConnection;
    //是否连接成功
    public static boolean isConnect;

    //必须要在主线程，不然不会显示
    @SuppressLint("HandlerLeak")
    public static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x123:
                    String msgJosn = msg.obj.toString();
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.ACCEPTMSG);
                    messageEvent.setMessageValue(msgJosn);
                    EventBus.getDefault().post(messageEvent);
                    break;
                case 0x124:
                    String msgJosn2 = msg.obj.toString();
                    MessageEvent messageEvent2 = new MessageEvent();
                    messageEvent2.setMessageKey(EventConstants.ACCEPTMSG2);
                    messageEvent2.setMessageValue(msgJosn2);
                    EventBus.getDefault().post(messageEvent2);
                    break;
                default:
            }
        }
    };
    private static MessageBean messageBean;


    public static void connection() {
        String token = SPUtil.getString(Constants.TOKEN);
        hubConnection = HubConnectionBuilder.create(Constants.CODEBUILD)
                .withAccessTokenProvider(Single.defer(() -> {
                    // Your logic here.
                    return Single.just(token);
                })).build();
        //创建连接
       /*if (hubConnection == null) {

        }*/

        //断开连接监听（这里一般不会走）
        hubConnection.onClosed(new OnClosedCallback() {
            @Override
            public void invoke(Exception exception) {
                 UItils.showToastSafe("已断开连接");
                 hubConnect();
            }
        });

        //与服务器交互，接收服务器的消息,ReceiveMsg为与服务器约定的方法，这里接收的是String
        hubConnection.on("broadcastMessage", new Action1<String>() {
            @Override
            public void invoke(String message) {//必须放在连接之前，方法名和后台约定的（子线程）
                //要展示接收到的消息一定要在主线程，不然会出现不显示等问题
                Logger.i("invoke----------------------");
                Logger.i(message.toString());
                Message msg = new Message();
                msg.obj = message;
                msg.what = 0x123;
                handler.sendMessage(msg);
            }
        }, String.class);

        //与服务器交互，接收服务器的消息,ReceiveMsg为与服务器约定的方法，这里接收的是String
        hubConnection.on("respMessage", new Action1<String>() {
            @Override
            public void invoke(String message) {//必须放在连接之前，方法名和后台约定的（子线程）
                //要展示接收到的消息一定要在主线程，不然会出现不显示等问题
                Logger.i("invoke----------------------");
                MessageBean  messageBean = JSON.parseObject(message, MessageBean.class);
                Logger.i(messageBean.toString());
                Message msg = new Message();
                msg.obj = message;
                msg.what = 0x124;
                handler.sendMessage(msg);
            }
        }, String.class);



        hubConnect();
    }

    public static void hubConnect() {
        try {
            hubConnection.start().blockingAwait();//开始进行连接
            isConnect = isConnected();//判断是否已经连接
            // connect.setText(isConnect ? "断开" : "连接");
            UItils.showToastSafe(isConnect ? "连接成功" : "连接失败");

        } catch (Exception e) {
            isConnect = false;
            UItils.showToastSafe("发生异常，请检查网络");
        }
    }


    /**
     * 检测是否连接
     */
    public static boolean isConnected() {
        //这样判断并不准确
        if (hubConnection != null && hubConnection.getConnectionState() == HubConnectionState.CONNECTED)
            return true;
        return false;
    }
}
